﻿using AutoMapper;
using Furion.DataEncryption;
using Furion.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using XinGuanERP.Db;
using XinGuanERP.Enums;
using XinGuanERP.Models.Po.system;
using XinGuanERP.Models.Vo.system;
using XinGuanERP.Services.system.IServices;

namespace XinGuanERP.Services.system
{
    public class UserLoginService : IUserLoginService, ITransient
    {
        private readonly DefaultDbContext _defaultDbContext;

        public UserLoginService(DefaultDbContext defaultDbContext)
        {
            _defaultDbContext = defaultDbContext;
        }
        public UserVo Login(UserLoginVo userLoginVo)
        {
            var username = userLoginVo.Username;
            var password = userLoginVo.Password;
            var res = _defaultDbContext.Users.Include(user => user.Role).FirstOrDefault(x => x.UserName == username);
            if (res != null)
            {
                if (res.PassWord == MD5Encryption.Encrypt(password))
                {
                    // 生成JWT
                    var TokenStr = JWTEncryption.Encrypt(new Dictionary<string, object>()
                    {
                        { "UserId", res.Id! },
                        { "UserName", res.UserName! },
                        { "RealName", res.RealName! },
                        { "Avatar", res.Avatar! },
                        { "RoleId", res.Role!.Id! },
                        { "HomePath", "/dashboard/analysis" }
                    });
                    var config = new MapperConfiguration(cfg =>
                        {
                            cfg.CreateMap<User, UserVo>()
                                .ForMember(d => d.username, opt => opt.MapFrom(src => src.UserName))
                                .AfterMap((src, des) => des.Roles = new Role[1] { src.Role! })
                                .AfterMap((src, des) => des.Token = "bearer " + TokenStr)
                                .ForMember(dest => dest.password, opt => opt.Ignore());
                        }
                    );
                    var mapper = config.CreateMapper();
                    return mapper.Map<UserVo>(res);
                }
            }
            return new UserVo();
        }
    }
}
